//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by mac on 15/8/6.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
private let HMErrorDomainName = "com.itheima.error.network"
/// 网络工具类
class NetworkTools: AFHTTPSessionManager {
    //  MARK:---应用信息
    private let clientId = "1202799366"
    private let appSecret = "1b757926be206f52458babae4b43467c"
    let redirectUri = "http://www.baidu.com"

    
    // 全局访问点
    static let shareTools:NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetworkTools(baseURL: baseURL)
//        设置数据解析类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
   
    }()
//    MARK:-  加载用户数据
    func loadUserInfo(uid: String,finished:HMNetFinishedCallBack) {
        
        // 判断 token 是否存在
        if UserAccount.loadAccount()?.access_token == nil {
            return
        }
        
        let urlString = "2/users/show.json"
        let params: [String: AnyObject] = ["access_token": UserAccount.loadAccount()!.access_token!, "uid": uid]
        
        // 发送网络请求
        // 提示：如果参数不正确，首先用 option + click 确认参数类型
        requestGET(urlString, params: params,finished:finished)            
        }
   

//    返回OAuth授权地址
    func oauthURL() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
//    使用code加载accessToken
    func loadAccessToken(code:String, finished:HMNetFinishedCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parames = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        POST(urlString, parameters: parames, success: { (_, JSON) -> Void in
            finished(result: JSON as? [String:AnyObject], error: nil)
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
    
//    MARK:----封装AFN网络方法,便于替换网络访问方法,第三方框架的代码全部集中于此
    typealias HMNetFinishedCallBack = (result:[String: AnyObject]?,error:NSError?)->()
    private func requestGET(urlString: String, params:[String: AnyObject],finished:HMNetFinishedCallBack){
        GET(urlString, parameters: params, success: { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
//                有结果的回调
                finished(result: result, error: nil)
            }else{
//                没有错误,同时没有结果
                print("没有数据")
                let error  = NSError(domain: HMErrorDomainName, code: -1, userInfo: ["errorMessage":"空数据"])
                finished(result: nil, error: error)
            }
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
    
    
    
    
    
    

}
